<?php
class liter_model extends MY_Model
{
	public
	//tables
		$table = 'literature',
		$prKey = 'lit_id',
		$tlink  = 'literature_sections',
		$tsections = 'sections';

	//using
    function __construct()
	{
       
		parent::__construct();

		//$this->bookSections = $this->getBooksSections();
		
		$this->fields = array(
			'id'				=> '',
			'description'		=> T_('Description'),
			'section'			=> T_('Section'),
			'subsection'		=> T_('Subsection'),
			'name'				=> T_('Name'),
			'author'			=> T_('Author'),
			'publishing_house'	=> T_('Publishing house'),
			'year'				=> T_('Year'),
			'mark'				=> T_('Mark'),
			);
		
		$this->rules = array(
			'description'		=> "trim|required|max_length[1000]",
			'name'				=> "trim|required|max_length[255]",
			'author'			=> "trim|required|max_length[255]",
			'publishing_house'	=> "trim|required|max_length[255]",
			'year'				=> "trim|required|max_length[4]",
			'mark'				=> "is_natural_no_zero",
			'section'			=> "is_natural_no_zero",
			'subsection'		=> "is_natural_no_zero",
		);
	}
	
	//using
  	function search($config = array())
	{
		$author				= $this->input->get_post('author');
		$name				= $this->input->get_post('name');
		$description		= $this->input->get_post('description');		
		$publishing_house	= $this->input->get_post('publishing_house');
		$year				= $this->input->get_post('year');

		//are not used in administrator pages
		$mark		= $this->input->get_post('mark');
		//$section	= $this->input->get_post('section');
		
		$order 		= $this->input->get_post('order');
		$direction 	= $this->input->get_post('direction');

		// main sql
		$sql = 'SELECT *';
		$sql .= ' FROM '.$this->table.' AS A';
		$sql .= ' WHERE 1 = 1';

		if ($author) {
			
			$sql .= ' AND (A.lit_author LIKE ' . $this->db->escape("%" . $author. "%") . ')';
		}
		
		if ($name) {
			
			$sql .= ' AND (A.lit_name LIKE ' . $this->db->escape("%" . $name. "%") . ')';
		}
		
		if ($description) {
			
			$sql .= ' AND (A.lit_description LIKE ' . $this->db->escape("%" . $description. "%") . ')';
		}
				
		if ($publishing_house){
			
			$sql .= ' AND A.lit_publishing_house='.$this->db->escape($publishing_house);
		}

		if ($year) {
			
			$sql .= ' AND A.lit_year>='.$this->db->escape($year);
		}
		
		if ($mark){
			
			$sql .= ' AND A.lit_mark='.$this->db->escape($mark);
		}
	
		switch ($order)
		{
			case 'date':
				$sql .= ' ORDER BY A.lit_year';
				break;

			default:
				$sql .= ' ORDER BY A.lit_author';
				$direction = 'DESC';
		}

		$sql .= ($direction == 'DESC') ? ' DESC' : ' ASC';
        
		$this->data['list'] = $this->db->query($sql)->result();
		
		if(empty($this->data['list'])){
                $this->data['message_error'] = "Didn't exist in data base.";
        } 
 	}	
  
  //using
  function getBook($id = null) {
  	
		$this->db->from($this->table);
		$this->db->where($this->prKey.' = '.$id);
		$query = $this->db->get();

		return $query->row_array();
	}

  //using
  function getBookLink($id = null){
  	
  		$this->db->from($this->tlink);
		$this->db->where('literature_id = '.$id);
		$query = $this->db->get();

		return $query->row_array();
  }
  
  //using
  function getBookSections($id = null) {
  	
		$this->db->from($this->tlink);
		$this->db->join($this->tsections, 'sections_id = section_id', 'LEFT');
		$this->db->where('literature_id = '.$id);
		$result = $this->db->get()->row_array();
		
		$response['section'] = "";
		$response['subsection'] = "";
		
		if(!empty($result)) {
			if($result['section_sub']==='0') {
				$response['section'] = $result['section_id'];
			} else {
				$response['subsection'] = $result['section_id'];
				$parent = $this->getSectionById($result['section_sub']);
				$response['section'] = $parent['section_id'];
			}
		}
		return $response;
	}
	
  //using
  function delete($items_serialized = null){
  	
		$items = explode("&", $items_serialized);

		$error = "";
		$report = "";
		foreach ($items as $id)
		{
			$data = $this->liter_model->getBook($id);
			$link = $this->getBookLink($id);
			
			$res = $this->db->delete($this->table, array($this->prKey => $id));
			$this->db->delete($this->tlink, array('literature_id' => $id));
			if (is_null($res))
			{
				$this->log->writeMessage('error', T_('Error. Page was not removed.'));
				$report .= ",0"; // don't deleted
			}
			else
			{
				$this->log->writeMessage('done', T_('Page was removed.'));
				$report .= ",1"; // deleted
			}
		}

		return substr($report, 1);
	}


  //using
  function insert($data, $section)
  {
    if (!empty($data))
    {
      
      parent::insert($data);

      $literature_id = $this->db->insert_id();
      if ($literature_id > 0){
        
      	$this->log->writeMessage('done', T_('Publication was successfully created.'));
		
        if(!empty($section)) {
	        
        	$section_el = $this->getSectionById($section);
	        
	        $section_data['sections_id'] 	= $section_el['section_id'];
	        $section_data['literature_id'] 	= $literature_id;
	        
	        $this->db->insert($this->tlink, $section_data);
	        if ($this->db->insert_id() > 0){
	        	
	        
      			$this->log->writeMessage('done', T_('Link was successfully created.'));
      		} else {
      			
      			$this->log->writeMessage('error', T_('Error! Link was not created. '.$section_data['sections_id'].''.$section_data['literature_id']));
      			return FALSE;	
	        }
        return TRUE;
      } else {
        $this->log->writeMessage('error', T_('Error! Link was not created.'));
        
        return FALSE;
      }
    }   
  }
 }
  function update($data, $section_data) {
  	
    if (!empty($data))
    {
      $res = parent::update($data);
		
      if($section_data){
      	
        $this->db->where('litsec_id', $section_data['litsec_id']);//$booklink['litsec_id']);
        unset($section_data['litsec_id']);
		$this->db->update($this->tlink, $section_data);
      }	
         					
	  $this->log->writeMessage('done', T_('The data saved successfully.'));
		
      return TRUE;      
    }   
  }
  
  function getBooks($section_id){
		$this->db->from($this->table);
		$this->db->join($this->tlink, $this->table.'.'.$this->prKey.' = '.$this->tlink.'.section_id', 'left');
		$this->db->where($this->table.'.'.$this->prKey, $section_id);
		$query = $this->db->get();

		return $query->row_array();
	}

	function getSections(){
		$this->db->from($this->tsections);
		$this->db->where('section_sub', '0');
		$query = $this->db->get();

		return $query->row_array();
	}
	
	//using
	function getSubsections($section_id){
		$this->db->from($this->tsections);
		$this->db->where('section_sub', $section_id);
		$query = $this->db->get();

		return $query->result_array();		
	}
	
	//using
	function getSectionById($id){
		$this->db->from($this->tsections);
		$this->db->where('section_id', $id);
		$query = $this->db->get();

		return $query->row_array();
		
	}
	
	//using
	function getSectionByName($name){
		$this->db->from($this->tsections);
		$this->db->where('section_name', $name);
		$query = $this->db->get();

		return $query->row_array();
		
	}
	
	//using
	function getBooksSections(){
		
		$sql = 'SELECT *';
		$sql .= ' FROM '.$this->tlink.' AS A';
		$sql .= ' LEFT OUTER JOIN '.$this->tsections.' AS B ON B.section_id = A.sections_id';
		
		return $this->db->query($sql)->result();
	}
	
}
 
?>